package com.tingyuge.io.sqlSession;

import com.tingyuge.io.pojo.Configuration;
import com.tingyuge.io.pojo.MappedStatement;

import javax.management.relation.Relation;
import javax.sql.DataSource;
import java.lang.reflect.*;
import java.sql.Connection;
import java.sql.Statement;
import java.util.List;

/**
 * @author xiaodao
 * @version 1.0
 * @date 2021/6/6
 */
public class DefaultSqlSession implements SqlSession {
    private Configuration configuration;

    public DefaultSqlSession(Configuration configuration) {
        this.configuration = configuration;
    }

    public <E> List<E> selectList(String statementId, Object... params) throws Exception {
        // 将要去完成 simpleExecutorQuery query
        SimpleExecutor simpleExecutor = new SimpleExecutor();
        MappedStatement mappedStatement = configuration.getMappedStatementMap().get(statementId);
        List<Object> query = simpleExecutor.query(configuration, mappedStatement, params);
        return (List<E>) query;
    }

    public <T> T selectOne(String statementId, Object... params) throws Exception {
        List<Object> objects = selectList(statementId, params);
        if (objects.size() == 1) {
            return (T) objects.get(0);
        } else if (objects.size() == 0) {
            return null;
        } else {
            throw new RuntimeException("expect one but get two! ");
        }
    }

    public <T> T getMapper(Class<?> mapperClass) {

        //使用JDK 动态代理来为dao接口生成代理对象. 并返回

        Object proxyInstance = Proxy.newProxyInstance(this.getClass().getClassLoader(), new Class[]{mapperClass}, new InvocationHandler() {
            //proxy.当前代理对象的引用
            //method :当前被调用方法的引用 .就是IUserDao.findAll 的引用
            //args: 传递的参数
            public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
                //底层都去执行JDBC代码// 根据不同的场景 来调用selectOne  selectList

                //装备参数1.statementId:  Sql语句的唯一标识. namespace.id  接口全限定名.方法名 .
                String methodName = method.getName();
                String className = method.getDeclaringClass().getName();
                String statementId = className+"."+methodName;

                //装备参数2: param:args
                //获取被调用方法的返回值类型
                Type genericReturnType = method.getGenericReturnType();
                //判断是否进行了 泛型参数化

                if(genericReturnType instanceof ParameterizedType){
                    List<Object> objects = selectList(statementId, args);
                    return objects;
                }
                return selectOne(statementId, args);
            }
        });
        return (T) proxyInstance;
    }
}
